using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using JQuery.WebKit.Base;
using JQuery.WebKit.WebCommon;

[assembly: WebResource("JQuery.WebKit.JInputListField.JInputListField.js", "text/javascript")]
[assembly: WebResource("JQuery.WebKit.JInputListField.JInputListField.min.js", "text/javascript")]
[assembly: WebResource("JQuery.WebKit.JInputListField.JInputListField.css", "text/css")]

namespace JQuery.WebKit
{
    [ParseChildren(typeof(string), DefaultProperty = "ListItems", ChildrenAsProperties = true)]
    public class JInputListField : WebControlBase, INamingContainer
    {
        private HtmlInputHidden _itemTracker;
        private HtmlSelect _itemListContainer;
        private HtmlInputButton _addButton;
        private HtmlInputButton _removeButton;
        private HtmlInputText _inputText;
        private List<string> _list;

        private bool rendered;

        [PersistenceMode(PersistenceMode.InnerProperty),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public List<string> ListItems
        {
            get
            {
                if (!Page.IsPostBack)
                    return _list;
                return GetListItems();
            }
        }

        public JInputListField()
            : base(HtmlTextWriterTag.Div)
        {
            _list = new List<string>();
        }

        public int ListAreaHeight { get; set; }
        public int ListAreaWidth { get; set; }
        public int TextWidth { get; set; }
        public string FieldName { get; set; }

        public int ButtonsAreaWidth { get; set; }
        public int InputAreaWidth { get; set; }
        public int InputFieldWidth { get; set; }

        public HtmlControl ItemTracker
        {
            get { return _itemTracker; }
        }

        protected override void CreateChildControls()
        {
            _itemTracker = new HtmlInputHidden {ID="itemTracker", EnableViewState = false};
            this.Controls.Add(_itemTracker);

            _inputText = new HtmlInputText() ;
            if (InputFieldWidth > 0)
                _inputText.Attributes.Add("style", string.Format("width: {0}px;", InputFieldWidth));

            _itemListContainer = new HtmlSelect();
            _itemListContainer.Attributes.Add("multiple", "multiple");
            _itemListContainer.Attributes.Add("style",
                                              string.Format("width: {0}; height: {1}",
                                                            ListAreaWidth > 0 ? ListAreaWidth + "px" : "100%",
                                                            ListAreaHeight > 0 ? ListAreaHeight + "px" : "50px"));
            
            _addButton = new HtmlInputButton("button");
            _addButton.Attributes.Add("class", "ui-state-default ui-corner-all");
            _addButton.Attributes.Add("value", ">");
            _removeButton = new HtmlInputButton("button");
            _removeButton.Attributes.Add("class", "ui-state-default ui-corner-all");
            _removeButton.Attributes.Add("value", "<");


            var tempTable = new HtmlTable {Width = "100%"} ;
            var aeroWindow = FindControlParent(this, typeof(AeroWindow));
            tempTable.Attributes.Add("onmouseover", string.Format("setInitialValues('{0}', '{1}');", _itemTracker.ClientID, aeroWindow.ClientID));

            var tableRow = new HtmlTableRow();
            var inputCell = new HtmlTableCell {Width = string.Format("{0}", InputAreaWidth > 0 ? InputAreaWidth + "px" : "45%")};
            inputCell.Attributes.CssStyle.Add("text-align", "left");
            if (TextWidth > 0)
                inputCell.Attributes.CssStyle.Add("width", TextWidth.ToString()); //Due to table nesting, -5px should be made
            

            var table = new HtmlTable
            {
                Controls = {
                new HtmlTableRow {Controls = 
                    {
                        new HtmlTableCell { InnerHtml = FieldName, Width = (TextWidth-5).ToString()}, 
                        new HtmlTableCell { Controls = {_inputText}}
                    }
            }}};
            table.Attributes.CssStyle.Add("width","100%");
            inputCell.Controls.Add(table);


            var button1Cell = new HtmlTableCell { Width = string.Format("{0}px", ButtonsAreaWidth > 0 ? ButtonsAreaWidth.ToString() : "30" )};
            button1Cell.Controls.Add(_addButton);
            var listCell = new HtmlTableCell {RowSpan = 2};
            listCell.Controls.Add(_itemListContainer);
            tableRow.Controls.Add(inputCell);
            tableRow.Controls.Add(button1Cell);
            tableRow.Controls.Add(listCell);
            var anotherRow = new HtmlTableRow();
            var button2Cell = new HtmlTableCell();
            button2Cell.Controls.Add(_removeButton);
            anotherRow.Controls.Add(new HtmlTableCell());
            anotherRow.Controls.Add(button2Cell);

            tempTable.Controls.Add(tableRow);
            tempTable.Controls.Add(anotherRow);
            
            this.Controls.Add(tempTable);
            
        }

        protected override void OnPreRender(EventArgs e)
        {
            var aeroWindow = FindControlParent(this, typeof(AeroWindow));

            ListItems.ForEach(item => _itemListContainer.Items.Add(item));
            
            _itemTracker.Value = string.Join("|", ListItems.Select(item => string.Format("{{{0}}}|", item)).ToArray());
            _addButton.Attributes.Add("onclick",
                                      string.Format("addListOption('{0}', '{1}', $('#{2}').val(),  $('#{2}').val(), '{3}'); $('#{2}').val('');return false;",
                                                    _itemListContainer.ClientID, _itemTracker.ClientID, _inputText.ClientID, aeroWindow.ClientID));
            _removeButton.Attributes.Add("onclick",
                                         string.Format("removeListOption('{0}', '{1}', '{2}');return false;", _itemListContainer.ClientID,
                                                       _itemTracker.ClientID, aeroWindow.ClientID));
  
            HtmlUtil.RegisterResource(this.GetType(), Globals.ResourcePaths.JQueryLibraries.JQuery, ResourceType.Javascript);
            base.RegisterJQueryResource("JQuery.WebKit.JInputListField.JInputListField.js");
            base.RegisterCSSResource("JQuery.WebKit.JInputListField.JInputListField.css");            
            base.OnPreRender(e);
            rendered = true;
        }

        private static Control FindControlParent(Control control, Type type)
        {
            Control ctrlParent = control;
            while ((ctrlParent = ctrlParent.Parent) != null)
            {
                if (ctrlParent.GetType() == type)
                {
                    return ctrlParent;
                }
            }
            return null;
        }

        public override void RenderBeginTag(HtmlTextWriter writer)
        {
            base.CssClass = "jlist";
            base.RenderBeginTag(writer);
        }


        private List<string> GetListItems()
        {
            var usableList  = new List<string>();

            if (Page.PageData["fieldValues"] == null)
            {
                return usableList;
            }

            var itemStringList = Page.PageData["fieldValues"].ToString().Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

            for (int i = 0; i < itemStringList.Length; i++)
            {
                itemStringList[i] = itemStringList[i].Trim().Replace("{", "");
                itemStringList[i] = itemStringList[i].Trim().Replace("}", "");
                string[] kyVal = itemStringList[i].Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                usableList.Add(kyVal[kyVal.Length-1]);
            }
            return usableList;
        }


    }
}
